import Taro from '@tarojs/taro'
import interceptors from './interceptors'

export type HeaderType = { [key: string]: string };
export type OtherRequestOptionsType = Omit<Taro.request.Option, 'url' | 'data' | 'method'>;

interceptors.forEach(interceptorItem => Taro.addInterceptor(interceptorItem))

export async function request(params: Taro.request.Option) {
  const { url, method = "GET", data = {}, header = {}, ...rest } = params;
  const headers: HeaderType = {
    'content-type': "application/json",
    ...header
  }
  if(Taro.getStorageSync('token')){
    headers['Authorization'] = "Bearer " + Taro.getStorageSync('token');
  }

  return Taro.request({
    url: url,
    data: data,
    method: method,
    header: headers,
    ...rest
  });
}

export const get = (url: string, data = {}, rest: OtherRequestOptionsType = {}) => {
  return request({ url, method: "GET", data, ...rest });
}

export const post = (url: string, data = {}, rest: OtherRequestOptionsType = {}) => {
  return request({ url, method: "POST", data, ...rest });
}

export const put = (url: string, data = {}, rest: OtherRequestOptionsType = {}) => {
  return request({ url, method: "PUT", data, ...rest });
}

export const del = (url: string, data = {}, rest: OtherRequestOptionsType = {}) => {
  return request({ url, method: "DELETE", data, ...rest });
}

